<template>
  <div class="wrapLimit clx main">
    <div class="order-detail">
      <el-form :model="data" class="form-baseinfo">
        <div class="orderInfo">
          <p class="title">订单基本信息</p>
          <div class="info">
            <el-form-item label=" 订单号：" prop="">
              <span>{{ data.soNo }}</span>
              <!-- <el-input readonly v-model="data.soNo"></el-input> -->
            </el-form-item>
            <el-form-item label="结算时间：" prop="">
              <span>{{ data.settlementDate }}</span>
              <!-- <el-input readonly v-model="data.settlementDate"></el-input> -->
            </el-form-item>
            <el-form-item label="结算方式：" prop="">
              <span>{{ data.payType }}</span>
              <!-- <el-input readonly v-model="data.settlementDate"></el-input> -->
            </el-form-item>
            <!-- <el-col :span="8">
            <el-form-item label="操作人：" prop="">
              <span>{{ data.createName }}</span>
            </el-form-item>
           -->
            <el-form-item label="订单金额：" prop="">
              <span>{{ data.soMoney }}</span>
              <!-- <el-input readonly v-model="data.soMoney"></el-input> -->
            </el-form-item>
            <el-form-item label="结算金额：" prop="">
              <span>{{ data.settlementMoney }}</span>
            </el-form-item>
            <el-form-item label="订单状态：" prop="">
              <span>{{ data.statusName }}</span>
              <!-- <el-input readonly v-model="data.statusName"></el-input> -->
            </el-form-item>
            <el-form-item label="创建时间：" prop="">
              <span>{{ data.createTime }}</span>
              <!-- <el-input readonly v-model="data.createTime"></el-input> -->
            </el-form-item>
          </div>
        </div>
      </el-form>

      <el-form :model="data" class="form-baseinfo">
        <div class="orderInfo">
          <p class="title">下单用户信息</p>

          <div class="info">
            <el-form-item label="员工姓名：" prop="">
              <span>{{ data.userName }}</span>
              <!-- <el-input readonly v-model="data.userName"></el-input> -->
            </el-form-item>

            <el-form-item label="员工工号：" prop="">
              <span>{{ data.userJobNum }}</span>
              <!-- <el-input readonly v-model="data.userCardNo"></el-input> -->
            </el-form-item>

            <el-form-item label="所在部门：" prop="">
              <span>{{ data.departmentName }}</span>
              <!-- <el-input readonly v-model="data.departmentName"></el-input> -->
            </el-form-item>

            <el-form-item label="岗位：" prop="">
              <span>{{ data.jobName }}</span>
              <!-- <el-input readonly v-model="data.jobName"></el-input> -->
            </el-form-item>

            <el-form-item label="员工卡号：" prop="">
              <span>{{ data.userCardNo }}</span>
              <!-- <el-input readonly v-model="data.jobName"></el-input> -->
            </el-form-item>
          </div>
        </div>
      </el-form>

      <div class="form-baseinfo">
        <div class="orderInfo">
          <p class="title">订单产品信息</p>
          <LPTablePage
            :show-index="true"
            :show-indexfixed="false"
            index-label="序号"
            :table-data="tableData"
            :table-column="tableColumn"
            :show-page="false"
            align="center"
          >
            <template slot="settlementMoney" slot-scope="{ row }" />
          </LPTablePage>
          <span class="collect"
            >汇总：一共{{ tableCount }}件商品（<span v-for="(item, index) in productDetail" :key="index">{{
              ' ' + item.pTitle + ' : ' + item.pCount + '；'
            }}</span
            >），总金额{{ totalMoney }}元</span
          >
        </div>
      </div>

      <div v-if="data.payType == '0'" class="form-baseinfo">
        <div class="orderInfo">
          <p class="title">订单使用优惠券情况</p>
          <LPTablePage
            :show-index="true"
            :show-indexfixed="false"
            index-label="序号"
            :table-data="couponData"
            :table-column="couponColumn"
            :show-page="false"
            align="center"
          >
            <template slot="startTime" slot-scope="{ row }">
              <div>{{ row.startTime + '--' + row.endTime }}</div>
            </template>
          </LPTablePage>
        </div>
      </div>
      <div style="margin-top: 10px">
        <el-button class="button" type="primary" size="meduim" @click="closeDetail">关闭</el-button>
        <el-button v-if="isSettle" class="button" type="primary" size="meduim" @click="settleOrder">结算</el-button>
      </div>

      <el-dialog
        class="settleDialog"
        title="结算详情"
        :visible.sync="settleVisb"
        width="30%"
        :before-close="settleclose"
      >
        <el-form ref="settleDialog" :inline="true" label-width="110px" :rules="rules" :model="settleDialog">
          <div v-if="settleData.settleState === 'success'" style="margin-top: 5px">
            <el-form-item label="姓名：" />

            <span>{{ settleData.userName }}</span>
            >

            <el-form-item label="岗位：" />

            <span>{{ settleData.jobName }}</span>
            >

            <el-form-item label="工号：" />

            <span>{{ settleData.userJobNum }}</span>
            >

            <el-form-item label="卡号：" />

            <span>{{ settleData.userCardNo }}</span>
            >

            <el-form-item label="结算金额：" />

            <span>{{ settleData.settlementMoney }}</span>
            >
          </div>

          <el-form-item label="结算状态：" />

          <div v-if="settleData.settleState === 'loading'">
            <i style="font-size: 20px" class="el-icon-loading" />
            <span style="font-size: 16px">结算中，请稍后</span>
          </div>
          <el-link
            v-else-if="settleData.settleState === 'success'"
            style="font-size: 16px"
            type="success"
            icon="el-icon-success"
            >结算成功</el-link
          >
          <el-link v-else style="font-size: 16px" type="danger" icon="el-icon-error">结算失败</el-link>
          >
          <el-form-item label="失败原因：" />

          <span>{{ settleData.message }}</span>
          <el-row
            v-if="settleData.settleState === 'error' || settleData.settleState === 'loading'"
            class="settleSuserCardNo"
          />
          <el-form-item label="员工卡号/工号：" />

          <el-form-item prop="userCardNo">
            <el-input v-model="settleDialog.userCardNo" />
          </el-form-item>
          <span slot="footer" class="dialog-footer button">
            <el-button v-if="settleData.settleState === 'error'" type="primary" @click="getCardDataAgainButton"
              >重新结算</el-button
            >
            <el-button v-else-if="settleData.settleState === 'success'" type="primary" @click="settleSave"
              >确 定</el-button
            >
            <el-button
              v-if="settleData.settleState === 'error' || settleData.settleState === 'loading'"
              type="primary"
              @click="manualSettle('settleDialog')"
              >手动结算</el-button
            >
            <el-button
              v-if="settleData.settleState === 'error' || settleData.settleState === 'loading'"
              type="info"
              @click="settleclose"
              >取 消</el-button
            >
          </span>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { getByIdOrderData, settleByIdOrder, getCardData, getOrderCouponList } from '@/api/LaborProtection/order'
import { closeActiveTag, parseTime } from '@/utils/lpUtils.js'
import LPTablePage from '@/components/LPTablePage/index.vue'

export default {
  name: 'OrderDetail',
  components: { LPTablePage },
  data() {
    return {
      id: '',
      NewTime: '',
      TimingTime: '',
      inventoryType: 0,
      data: {},
      settleData: {
        userName: '',
        settlementMoney: '',
        userCardNo: '',
        userJobNum: '',
        jobName: '',
        message: '',
        settleState: ''
      },
      productDetail: [],
      settleDialog: {
        userCardNo: ''
      },
      tableData: [],
      // 表格字段
      tableColumn: [
        { label: '物料类型', prop: 'pClassName' },
        { label: '物料编码', prop: 'pNo' },
        // {label: "单位", prop: "unit"},
        { label: '物料名称', prop: 'pTitle' },
        { label: '产品销售单价', prop: 'pPrice' },
        { label: '数量', prop: 'pCount' },
        { label: '产品总价', prop: 'pMoney' },
        { label: '产品金额', prop: 'settlementMoney' }
      ],
      couponData: [],
      // 表格字段
      couponColumn: [
        { label: '发放记录编码', prop: 'recordId' },
        { label: '优惠券名称', prop: 'couponName' },
        { label: '优惠券有效期', prop: 'startTime', render: true },
        { label: '优惠券内容', prop: 'materialName' },
        { label: '抵扣数量', prop: 'count' }
      ],
      tableCount: 0,
      totalMoney: 0,
      isSettle: false,
      settleVisb: false,
      rules: {
        userCardNo: [{ required: true, message: '请输入卡号', trigger: 'blur' }]
      }
    }
  },
  mounted() {
    this.getByIdOrderData()
  },
  methods: {
    getByIdOrderData() {
      const query = JSON.parse(this.$route.query.data)
      console.log(query.isSettle)
      this.id = query.id
      this.isSettle = query.isSettle
      getByIdOrderData(this.id).then((res) => {
        this.data = res
        this.tableData = res.ordersProducts
        res.ordersProducts.forEach((item) => {
          this.totalMoney = this.totalMoney + item.pMoney
          this.tableCount = this.tableCount + item.pCount
        })
        if (res.ordersProducts.length == 0) return
        const map = new Map()
        const newArr = []
        for (const obj of res.ordersProducts) {
          if (!map.has(obj.pNo)) {
            map.set(obj.pNo, true)
            newArr.push(obj)
          }
        }
        const productArr = []
        newArr.forEach((item) => {
          let tempData = 0
          res.ordersProducts.forEach((tempItem) => {
            if (item.pNo == tempItem.pNo) {
              tempData = tempData + tempItem.pCount
            }
          })
          productArr.push({
            pNo: item.pNo,
            pTitle: item.pTitle,
            pCount: tempData
          })
        })
        this.productDetail = productArr
        console.log(productArr)
      })
      getOrderCouponList(this.id).then((res) => {
        this.couponData = res
      })
    },
    closeDetail() {
      const query = JSON.parse(this.$route.query.data)
      if (typeof query.lType !== 'undefined') {
        if (query.lType == 1) {
          return closeActiveTag(this, '/laborProtection/order/salesFlow')
        } else {
          return closeActiveTag(this, '/laborProtection/inventoryControl/flowRecord/index')
        }
      }
      if (typeof query.returnOrderId !== 'undefined') {
        this.$router.push({
          path: '/laborProtection/order/returnOrderManage/detail',
          query: {
            data: JSON.stringify({
              id: query.returnOrderId,
              isAudit: false
            })
          }
        })
        // closeActiveTag('/order/detail');
      } else {
        closeActiveTag(this, '/laborProtection/order')
      }
    },
    settleOrder() {
      console.log(this.data.equipmentNO)
      if (this.data.equipmentNO != localStorage.getItem('equipmentNumber')) {
        return this.$message.error('该订单设备号与本地存储的设备号不一致，请作废')
      }
      if (localStorage.getItem('warehouseType') == null) {
        this.inventoryType = 0
      } else {
        this.inventoryType = 1
      }
      const temp = new Date()
      this.TimingTime = new Date()
      this.settleTime = parseTime(temp)
      this.settleData.settleState = 'loading'
      this.settleVisb = true
      const data = {
        deviceNo: this.data.equipmentNO
      }
      getCardData(data).then((cardData) => {
        if (parseTime(cardData.data.rT_BODY.xfrqsj) > this.settleTime) {
          const settleDate = {
            id: this.id
          }
          settleByIdOrder(settleDate)
            .then((settle) => {
              this.settleData.message = ''
              this.settleData.jobName = settle.data.jobName
              this.settleData.userName = settle.data.userName
              this.settleData.userCardNo = settle.data.userCardNo
              this.settleData.userJobNum = settle.data.userJobNum
              this.settleData.settlementMoney = settle.data.settlementMoney
              this.settleData.settleState = 'success'
              this.settleVisb = true
            })
            .catch((err) => {
              this.settleData.settleState = 'error'
              this.settleVisb = true
              this.settleData.message = err.response.data.error.message
            })
        } else {
          this.getCardDataAgain(this.TimingTime)
        }
      })
    },
    getCardDataAgainButton() {
      this.settleDialog = {
        userCardNo: ''
      }
      this.settleData.settleState = 'loading'
      // 每次点击重新结算按钮时，去拿点击的时间
      this.TimingTime = new Date()
      this.getCardDataAgain(this.TimingTime)
    },
    getCardDataAgain(Timing) {
      const data = {
        deviceNo: this.data.equipmentNO
      }
      getCardData(data).then((cardData) => {
        if (parseTime(cardData.data.rT_BODY.xfrqsj) > this.settleTime) {
          const settleDate = {
            id: this.id
          }
          settleByIdOrder(settleDate)
            .then((settle) => {
              this.settleData.message = ''
              this.settleData.jobName = settle.data.jobName
              this.settleData.userName = settle.data.userName
              this.settleData.userCardNo = settle.data.userCardNo
              this.settleData.userJobNum = settle.data.userJobNum
              this.settleData.settlementMoney = settle.data.settlementMoney
              this.settleData.settleState = 'success'
            })
            .catch((err) => {
              this.settleData.message = err.response.data.error.message
              this.settleData.settleState = 'error'
            })
        } else {
          const NewTime = new Date()
          const tempSettleTime = new Date(Timing).setMinutes(new Date(Timing).getMinutes() + 1)
          if (parseTime(NewTime) > parseTime(tempSettleTime)) {
            this.settleData.message = '获取支付信息超时'
            return
          } else {
            setTimeout(() => {
              this.getCardDataAgain(this.TimingTime)
            }, 1000)
          }
        }
      })
    },
    manualSettle(settleDialog) {
      this.$refs[settleDialog].validate((valid) => {
        if (valid) {
          const data = {
            id: this.id,
            userCardNo: this.settleDialog.userCardNo
          }
          settleByIdOrder(data)
            .then((res) => {
              this.settleData.message = ''
              this.settleData.jobName = res.data.jobName
              this.settleData.userName = res.data.userName
              this.settleData.userCardNo = res.data.userCardNo
              this.settleData.userJobNum = res.data.userJobNum
              this.settleData.settlementMoney = res.data.settlementMoney
              this.settleData.settleState = 'success'
            })
            .catch((err) => {
              this.settleData.settleState = 'errr'
              this.settleData.message = err.response.data.error.message
            })
        } else {
          return false
        }
      })
    },
    settleSave() {
      this.settleData = {
        userName: '',
        settlementMoney: '',
        userCardNo: '',
        userJobNum: '',
        jobName: '',
        message: '',
        settleState: ''
      }
      this.settleDialog = {
        userCardNo: ''
      }
      this.TimingTime = ''
      this.settleVisb = false
      this.closeDetail()
    },
    settleclose() {
      this.$confirm('结算未完成，是否退出', '提示', {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        type: 'warning'
      }).then(() => {
        this.settleVisb = false
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.order-detail {
  height: 1400px;
  .form-baseinfo {
    margin: 0 45px;
    .title {
      font-size: 16px;
      font-weight: 550;
    }
  }

  .settleDialog {
    .settleSuserCardNo {
      ::v-deep .el-form-item__label {
        line-height: 40px;
      }
    }

    ::v-deep .el-form-item__label {
      font-size: 15px;
    }

    ::v-deep .el-form-item__content {
      // width: 160px;

      line-height: 20px;
    }

    span {
      font-size: 16px;
    }
  }
}

::v-deep .el-form-item {
  height: 40px;
  margin-bottom: 2px;
}

::v-deep .el-form-item__label {
  font-weight: normal;
  color: #666666;
  line-height: 17px;
  padding: 0;
}

::v-deep .el-form-item__content {
  // width: 300px;
  line-height: 17px;
}
.orderInfo {
  .info {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    align-items: center;
    // margin: 0 45px;
    border-bottom: 1px solid #ededed;

    .el-form-item {
      width: calc(33%);
      height: 40px;
    }
  }
  .collect {
    display: block;
    padding-left: 20px;
    width: 100%;
    height: 40px;
    line-height: 40px;
    background-color: #f2f3f5;
  }
}

.title {
  margin-left: 10px;
  padding: 20px 0 20px 0;
  font-size: 18px;
  &::before {
    content: '';
    display: inline-block;
    width: 3px;
    height: 16px;
    position: absolute;
    left: 45px;
    background: #0076ff;
  }
}

.log {
  .title {
    padding-bottom: 30px;
  }
}

.button {
  width: 100px;
  position: relative;
  left: 50%;
  top: 30px;
  transform: translate(-50%);
}
</style>
